package com.cares.core.mng.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.cares.core.base.controller.BaseController;
import com.cares.core.mng.service.AccountService;
import com.cares.core.mng.service.OrgService;
import com.cares.core.utils.StringUtil;
import com.cares.entity.base.DataGridModel;
import com.cares.entity.base.PageModel;
import com.cares.entity.mng.Orgnization;
import com.cares.entity.mng.User;

/**
 * 管理员管理用户的Controller.
 * 
 * @author
 */
@Controller
@RequestMapping(value = "/Mng/user")
public class UserAdminController extends BaseController {

	@Autowired
	@Qualifier("accountService")
	private AccountService accountService;

	@Autowired
	@Qualifier("orgService")
	OrgService orgService;

	/**
	 * GET方法，用户列表页面加载
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String init() {
		return "frm/account/userList";
	}

	/**
	 * 查询用户列表信息
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public void getDateGrid(DataGridModel dgm, User user,
			HttpServletRequest req, HttpServletResponse response) {
		int pageNo = dgm.getPage();
		int pageSize = dgm.getRows();
		String order = dgm.getOrder();
		String sort = dgm.getSort();
		String orgCode = accountService.getCurrentUserOrgCode();
		//user.setOrgCode(orgCode);
		req.setAttribute("orgCode", orgCode);
		PageModel<User> pageModel = new PageModel<User>(pageNo, pageSize);
		pageModel.setOrder(order);
		pageModel.setSort(sort);
		pageModel.setCondition(user);
		String result = "";
		if (null != orgCode) {
			result = this.accountService.getOrgUsers(pageModel);
		}
		// XXX
		try {
			this.renderText(response, result);
		} catch (IOException e) {
		}
	}

	/**
	 * 根据组织机构Code查询机构下用户
	 * @param orgCode
	 * @param dgm
	 * @param user
	 * @param response
	 */
	@RequestMapping(value = "/org/{orgCode}", method = RequestMethod.POST)
	public void getorgDateGrid(@PathVariable("orgCode")
	String orgCode, DataGridModel dgm, User user, HttpServletResponse response) {

		int pageNo = dgm.getPage();
		int pageSize = dgm.getRows();
		String order = dgm.getOrder();
		String sort = dgm.getSort();
		user.setOrgCode(orgCode);
		PageModel<User> pageModel = new PageModel<User>(pageNo, pageSize);
		pageModel.setOrder(order);
		pageModel.setSort(sort);
		pageModel.setCondition(user);
		if (StringUtil.isNotEmpty(orgCode)) {
			String result = this.accountService.getUsers(pageModel);

			System.out.println(result);
			try {
				this.renderText(response, result);
			} catch (IOException e) {
			}
		}
	}
	
	/**
	 * 跳转至新增或修改页面
	 * @return
	 */
	@RequestMapping(value = "/addWin", method = RequestMethod.GET)
	public String addWin() {
		return "frm/account/userAdd";
	}
	
	/**
	 * 跳转至密码修改页面
	 * @return
	 */
	@RequestMapping(value = "/passWin", method = RequestMethod.GET)
	public String passWin() {
		return "frm/account/modiPass";
	}
	
	/**
	 * 修改密码
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/updatePass", method = RequestMethod.POST)
	public String updatePass(HttpServletRequest req) {
		Map<String, String> map = new HashMap<String, String>(1);
		try {
			String newpwd = req.getParameter("password");
			String oldpwd = req.getParameter("oldpwd");
			int r = accountService.updateUserPwd(accountService
					.getCurrentUser().getId(), newpwd, oldpwd);
			if (r == 0) {
				req.setAttribute("infoMsg", "更新失败！用户密码错误！");
			} else {
				map.put(AJAX_MESSAGE, "true");
			}
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("infoMsg", "更新失败！");
		}
		return SUCCESS_PAGE;
	}
	
	/**
	 * 密码重置
	 * @param uid
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/resetUserPwd/{uid}", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, String> resetPwd(@PathVariable("uid")
	Long uid, HttpServletRequest req) {
		Map<String, String> map = new HashMap<String, String>();
		map.put(AJAX_MESSAGE, "false");
		try {
			int r = accountService.updateResetUserPwd(uid,
					accountService.DEFAULT_PWD, accountService.DEFAULT_PWD);
			if (r == 0) {
				map.put("infoMsg", "更新失败！无效的用户信息！");
			} else {
				map.put(AJAX_MESSAGE, "true");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("infoMsg", "更新失败！");
		}
		return map;
	}
	
	/**
	 * 新增或修改用户
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/addOrUpdateUser", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, String> addOrUpdate(@RequestBody
	User user) {
		Map<String, String> map = new HashMap<String, String>(1);
		try {
			boolean cc = false;
			User check = accountService.findUserByLoginName(user.getLoginName());
			if (check != null) {
				if (null != user.getId()) {
					if (check.getId().intValue() != user.getId().intValue()) {
						cc = true;
					}
				} else {
					cc = true;
				}
			}

			if (cc) {
				map.put(AJAX_MESSAGE, "false");
				map.put("check_name", "false");
				return map;
			}
			if(null==user.getOrgId()){
				user.setOrgId(accountService.getCurrentUserOrgId());
			}
			Orgnization org = orgService.get(user.getOrgId());
			if (null != org) {
				user.setOrgnization(org);
				if (null != user.getId()) {
					accountService.updateUser(user);
					accountService.updateUserRoles(user);
				} else {
					accountService.updateNewUser(user);
					accountService.updateUserRoles(user);
				}
				map.put(AJAX_MESSAGE, "true");
			}else{
				map.put("infoMsg", "用户机构不存在！");
				map.put(AJAX_MESSAGE, "fasle");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("check_name", "false");
			map.put(AJAX_MESSAGE, "fasle");
		}
		return map;
	}
	
	/**
	 * 用户更新
	 * @param user
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid
	@ModelAttribute("preloadUser")
	User user, RedirectAttributes redirectAttributes) {
		accountService.updateUser(user);
		redirectAttributes.addFlashAttribute("message", "更新用户"
				+ user.getLoginName() + "成功");
		return "redirect:/admin/user";
	}
	
	/**
	 * 用户删除
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "delete/{id}")
	public @ResponseBody
	Map<String, String> delete(@PathVariable("id")
	List<String> ids) {
		Map<String, String> map = new HashMap<String, String>(1);
		try {
			List<Long> mid = new ArrayList<Long>();
			for (String cid : ids) {
				mid.add(Long.parseLong(cid));
			}
			for (Long id : mid) {
				accountService.deleteUser(id);
			}
			map.put(AJAX_MESSAGE, "true");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
		}
		return map;
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出User对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadUser")
	public User getUser(@RequestParam(value = "id", required = false)
	Long id) {
		if (id != null) {
			return accountService.getUser(id);
		}
		return null;
	}
}
